<template>
  <div class="container">
    <!-- 头部操作区 -->
    <div class="header">
      <h2>轮播图管理</h2>
      <el-button type="primary" @click="handleAdd">新增轮播图</el-button>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="输入标题或关键字">
          <el-input
            v-model="filterForm.keyword"
            placeholder="请输入..."
            clearable
          />
        </el-form-item>

        <el-form-item label="上传时间：">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <div class="table-header">
        <span>轮播图列表</span>
        <el-button
          type="danger"
          :disabled="!selectedIds.length"
          @click="batchDelete"
        >
          批量删除
        </el-button>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="carouselTitle" label="轮播图标题" width="180" />
        <el-table-column label="缩略图" width="120">
          <template #default="{ row }">
            <el-image
              :src="getFullUrl(row.thumbnail)"
              :preview-src-list="[getFullUrl(row.thumbnail)]"
              fit="cover"
              class="thumbnail"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ statusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createName" label="上传人" width="120" />
        <el-table-column prop="createTime" label="上传时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button type="danger" link @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import dayjs from 'dayjs';

import { useRouter } from 'vue-router';
const router = useRouter();
// API基础配置
const API_BASE = 'http://localhost:5223';
const IMAGE_BASE = 'http://localhost:5223'; // 图片服务器地址，如果和API_BASE相同，则无需修改
const API = {
  list: `${API_BASE}/api/CarouselimageQ/CarouselimageQuery`,
  delete: (id) => `${API_BASE}/api/CarouselimageD/CarouselimageDelete/${id}`
};

// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 分页
const currentPage = ref(1);
const pageSize = ref(15);
const total = ref(0);

// 筛选表单
const filterForm = reactive({
  keyword: '',
  dateRange: []
});

// 多选处理
const selectedIds = ref([]);
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map((item) => item.carouseId);
};

// 获取列表数据
const fetchList = async () => {
  try {
    loading.value = true;
    const params = {
      PageIndex: currentPage.value,
      PageSize: pageSize.value,
      CarouselTitle: filterForm.keyword,
      BeginTime: filterForm.dateRange[0] || '',
      EndTime: filterForm.dateRange[1] || ''
    };

    const res = await axios.get(API.list, { params });

    if (res.data?.code === 210) {
      tableData.value = res.data.list || [];
      total.value = res.data.totalCount || 0;
    } else {
      ElMessage.error(res.data?.msg || '获取列表失败');
    }
  } catch (err) {
    ElMessage.error('网络请求失败');
    console.error('接口错误:', err);
  } finally {
    loading.value = false;
  }
};

// 工具函数
const getFullUrl = (path) => {
  if (!path) return '';
  return path.startsWith('http') ? path : `${IMAGE_BASE}${path}`;
};

const statusText = (status) => {
  return status === 1 ? '上架' : '下架';
};

const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
};

// 页面加载时获取数据
onMounted(fetchList);

// 分页变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchList();
};

// 筛选
const handleFilter = () => {
  currentPage.value = 1;
  fetchList();
};

// 删除处理
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定删除该轮播图吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await axios.post(
      'http://localhost:5260/api/Carouselimage/CarouselimageDelete',
      {
        carouseId: row.carouseId
      }
    );

    if (res.data?.code === 204) {
      ElMessage.success('删除成功');
      fetchList();
    } else {
      ElMessage.error(res.data?.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除操作失败');
    }
  }
};

// 批量删除
const batchDelete = async () => {
  try {
    if (!selectedIds.value.length) return;

    await ElMessageBox.confirm(
      `确定删除选中的${selectedIds.value.length}项吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 这里假设后端支持批量删除，需要根据实际接口调整
    const deletePromises = selectedIds.value.map((id) =>
      axios.delete(API.delete(id))
    );
    await Promise.all(deletePromises);

    ElMessage.success('批量删除成功');
    fetchList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败');
    }
  }
};

// 新增/编辑（示例方法）
const handleAdd = () => {
  // 跳转到新增页面逻辑
  console.log('新增操作');
  router.push('/CarouselimageCreate');
};

const handleEdit = (row) => {
  router.push({ path: '/CarouselimageUpdate', query: { carouseId: row.carouseId } });
  console.log('编辑操作', row);
};
</script>

<style scoped>
/* 保持原有样式不变 */
.container {
  padding: 20px;
  background: #f5f7fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.thumbnail {
  width: 100px;
  height: 60px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-form--inline .el-form-item {
  margin-right: 30px;
}

.el-button--link {
  margin-right: 8px;
}
</style>
